#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 获取当前脚本文件所在目录的父目录，并构建相对路径
import os
import sys
current_dir = os.path.dirname(os.path.abspath(__file__))
project_path = os.path.join(current_dir, '..')
sys.path.append(project_path)
sys.path.append(current_dir)
import json
import gpCfg


# 示例 JSON 数据
json_data_in_gpJson = '''
{
    "name": "Alice",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Wonderland"
    },
    "skills": ["Python", "Data Analysis"]
}
'''

def gp_UpdateJsonFileFromFile(tgt, src):
    srcJson = gpCfg.GpCfg(src)
    gp_UpdateJsonFileFromObj(tgt, srcJson.cfg)

def gp_UpdateJsonFileFromObj(tgtFile, srcJsonObj):
    tgtJson = gpCfg.GpCfg(tgtFile)
    refresh_node(srcJsonObj, tgtJson.cfg, '')
    
    with open(tgtFile, 'w') as f2:
        json.dump(tgtJson.cfg, f2, indent=4)

def refresh_node(node, refreshed_data, parent_key):
    if isinstance(node, dict):
        for key, value in node.items():
            new_key = f"{parent_key}.{key}" if parent_key else key
            if isinstance(value, (dict, list)):
                refresh_node(value, refreshed_data, new_key)
            else:
                refreshed_data[new_key] = value
    elif isinstance(node, list):
        for i, item in enumerate(node):
            new_key = f"{parent_key}[{i}]"
            if isinstance(item, (dict, list)):
                refresh_node(item, refreshed_data, new_key)
            else:
                refreshed_data[new_key] = item

# 定义一个递归函数来遍历所有的键
def traverse_keys(d, gLevel=0):
    if isinstance(d, dict):
        for key in d:
            spaces = ' ' * gLevel
            print(spaces, key)
            # 递归遍历嵌套的字典
            gLevel = gLevel+1
            traverse_keys(d[key], gLevel)
            gLevel = gLevel-1
    elif isinstance(d, list):
        spaces = ' ' * gLevel
        print(spaces, "[array]") #array is a different type of node.
        gLevel = gLevel+1
        for item in d:
            # 递归遍历列表中的字典
            traverse_keys(item, gLevel)
        gLevel = gLevel-1
    else:
        #pass this branch can disp all no leaf nodes.
        #leaf nodes no need to step_in anymore.
        spaces = ' ' * gLevel
        print(spaces, d)


def find_nodes_by_name(root, keyname):
    data = root
    if isinstance(data, dict):
        for key, value in data.items():
            if key == keyname:
                return value
            result = find_labels(value)
            if result is not None:
                return result
    elif isinstance(data, list):
        for item in data:
            result = find_labels(item)
            if result is not None:
                return result
    return None